package com.web709.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.web709.entity.PointsAccounts;
import com.web709.entity.PointsTransactions;
import com.web709.mapper.PointsAccountsMapper;
import com.web709.mapper.PointsTransactionsMapper;
import com.web709.service.PointsTransactionsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Service
public class PointsTransactionsServiceImpl extends ServiceImpl<PointsTransactionsMapper, PointsTransactions> implements PointsTransactionsService {
    @Autowired
    private PointsTransactionsMapper pointsTransactionsMapper;

    @Autowired
    private PointsAccountsMapper pointsAccountsMapper;



    @Override
    public List<PointsTransactions> getByUserId(int userId) {
        QueryWrapper<PointsTransactions> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("volunteer_id", userId);
        List<PointsTransactions> pointsTransactions = pointsTransactionsMapper.selectList(queryWrapper);
        if (pointsTransactions.isEmpty()){
            PointsTransactions pointsTransactions1 = new PointsTransactions();
            pointsTransactions1.setUserId(userId);
            pointsTransactions1.setPointsChange(0);
            pointsTransactions1.setReason("无");
            pointsTransactions1.setTransactionDate(LocalDateTime.now());
            pointsTransactionsMapper.insert(pointsTransactions1);
        }
        return pointsTransactionsMapper.selectList(queryWrapper);
    }

    @Override
    public void exchangeProduct(Integer userId, Integer price,Integer productId) {
        //查出PointsTransactions去更新变化量
        QueryWrapper<PointsTransactions> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("volunteer_id", userId);
        List<PointsTransactions> p = pointsTransactionsMapper.selectList(queryWrapper);
        int pc = p.stream().mapToInt(PointsTransactions::getPointsChange).sum();
        QueryWrapper<PointsAccounts> pointsAccountsQueryWrapper = new QueryWrapper<>();
        pointsAccountsQueryWrapper.eq("volunteer_id", userId);
        PointsAccounts pointsAccounts = pointsAccountsMapper.selectOne(pointsAccountsQueryWrapper);
        pointsAccounts.setRemainingPoints(pc);


        PointsTransactions pointsTransactions = new PointsTransactions();
        pointsTransactions.setUserId(userId);
        pointsTransactions.setPointsChange(-price);
        pointsTransactions.setReason("兑换商品");
        pointsTransactions.setTransactionDate(LocalDateTime.now());
        pointsTransactionsMapper.insert(pointsTransactions);
    }
}

